package com.hup.utils.io.batch.function;

import com.hup.utils.io.batch.BaseBatch;
import com.hup.utils.io.batch.SimpleBatchResp;

import java.util.ArrayList;

/**
 * @author hugan
 * @date 2020/2/29
 */
public class Shutdown implements BaseBatch<SimpleBatchResp> {

    /**
     * 上次设置计划关机的关机时间,只能记录本程序启动的计划(批处理无法查询已有计划)
     */
    private static Long lastShutdownTime;
    
    /**
     * 取消关机计划
     */
    private boolean isCancel;
    /**
     * 计划关机时间
     */
    private int second;

    @Override
    public String cmd() {
        if (isCancel) {
            return "cmd /c shutdown /a 2>nul";
        } else {
            if(second != 0) {
                return "cmd /c shutdown /a 2>nul&shutdown /s /t " + second;
            } else {
                //锁屏时,要加'/f', 否则报错: 计算机已经锁定而且不使用强制选项无法关机。
                return "cmd /c shutdown /a 2>nul&shutdown /s /f /t " + second;
            }
        }
    }

    @Override
    public String desc() {
        return "计划关机";
    }

    @Override
    public SimpleBatchResp parse(ArrayList<String> lstResp) {
        if (!lstResp.isEmpty()) {
            return SimpleBatchResp.fail(this, lstResp);
        }
        if (isCancel) {
            lastShutdownTime = null;
        } else {
            //-100是当前时间迁移100ms,消除执行cmd的执行耗时;实际执行应该在100ms内
            lastShutdownTime = System.currentTimeMillis() + second * 1000 - 100;
        }
        return SimpleBatchResp.success();
    }

    public static Shutdown cancel() {
        Shutdown res = new Shutdown();
        res.isCancel = true;
        return res;
    }

    public static Shutdown shutdown(int second) {
        Shutdown res = new Shutdown();
        res.second = second;
        return res;
    }

    /**
     * 上次设置计划关机的关机时间,只能记录本程序启动的计划(批处理无法查询已有计划)
     */
    public static Long getLastShutdownTime() {
        return lastShutdownTime;
    }

}
